package com.useeinfo.oa.open.admin.inspection;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.lang.StringUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.FacilityCatBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.FacilityCat;
import com.useeinfo.oa.modules.inspection.biz.FacilityInspectionSnapBiz;
import com.useeinfo.oa.modules.inspection.biz.InspectionDataBiz;
import com.useeinfo.oa.modules.inspection.biz.InspectionTechnologyBiz;
import com.useeinfo.oa.modules.inspection.entity.FacilityInspectionSnap;
import com.useeinfo.oa.modules.inspection.entity.InspectionData;
import com.useeinfo.oa.modules.inspection.entity.InspectionOrder;
import com.useeinfo.oa.modules.inspection.entity.InspectionTechnology;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.modules.threadUtil.ThreadUtils;
import com.useeinfo.oa.open.admin.maintaining.MaintainTechnologyAction;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.List;

@Controller
@RequestMapping("/web/admin/inspectionTechnology")
public class InspectionTechnologyAction {
    @Autowired
    private InspectionTechnologyBiz inspectionTechnologyBiz;
    @Autowired
    private FacilityCatBiz facilityCatBiz;
    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private InspectionDataBiz inspectionDataBiz;

    @Autowired
    private FacilityInspectionSnapBiz facilityInspectionSnapBiz;

    private final static Logger logger = LoggerFactory.getLogger(InspectionTechnologyAction.class);

    private Workbook wb;
    private Sheet sheet;
    private Row row;

    @RequestMapping("/list")
    public ModelAndView list(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/inspection/inspectionTechnology/list");
        return modelAndView;
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "searchCode", required = false) String searchCode,
                               @RequestParam(value = "searchName", required = false) String searchName,
                               @RequestParam(value = "facilityCatId", required = false) String facilityCatId,//传此参数 表示此快照表和工艺的设备类型要一致
                               HttpServletRequest request) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        queryParam.getSqlMap().put("searchName",searchName);
        queryParam.getSqlMap().put("searchCode",searchCode);
        if (StringUtils.isNotBlank(facilityCatId)) {
            queryParam.getSqlMap().put("facilityCatId", facilityCatId);
        }
        JSONObject jsonObject = inspectionTechnologyBiz.findJSONList(queryParam);
        JSONArray jsonArray = jsonObject.getJSONArray("list");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject json = jsonArray.getJSONObject(i);
            Long catId = json.getLong("facilityCatId");
            json.put("rootCatName","");
            if(catId!=null){
                FacilityCat rootCat = facilityCatBiz.findRootCat(catId);
                if(rootCat!=null){
                    json.put("rootCatName",rootCat.getCatName());
                }
            }
        }
        return jsonObject;
    }

    @RequestMapping("/editPage")
    public ModelAndView editPage(@RequestParam(value = "id", required = false) String id,HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView();
        InspectionTechnology inspectionTechnology = inspectionTechnologyBiz.findModel(StringConverters.ToLong(id));
        Long timeStamp = System.currentTimeMillis();
        modelAndView.addObject("timeStamp",timeStamp);
        modelAndView.addObject("inspectionTechnology",inspectionTechnology);
        String rootCatId = "";
        if(inspectionTechnology!=null&&inspectionTechnology.getFacilityCat()!=null){
            FacilityCat rootCat = facilityCatBiz.findRootCat(inspectionTechnology.getFacilityCat().getId());
            rootCatId = rootCat.getId()+"";
        }
        modelAndView.addObject("rootCatId",rootCatId);
        modelAndView.setViewName("pages/admin/inspection/inspectionTechnology/edit");
        return modelAndView;
    }

    /**
     * 获取编辑页面（复制新增）
     */
    @RequestMapping("/copyEditPage")
    public ModelAndView copyEditPage(@RequestParam(value = "id", required = false) String id,HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        InspectionTechnology oldInspectionTechnology = inspectionTechnologyBiz.findModel(StringConverters.ToLong(id));
        InspectionTechnology newInspectionTechnology = new InspectionTechnology();
        if(oldInspectionTechnology!=null){
            newInspectionTechnology.setName(oldInspectionTechnology.getName());
            newInspectionTechnology.setFacilityCat(oldInspectionTechnology.getFacilityCat());
            newInspectionTechnology.setOrganization(oldInspectionTechnology.getOrganization());
            newInspectionTechnology.setEstimateTime(oldInspectionTechnology.getEstimateTime());
            newInspectionTechnology.setEffective(oldInspectionTechnology.isEffective());
            newInspectionTechnology.setRequireSkill(oldInspectionTechnology.getRequireSkill());
            newInspectionTechnology.setDescription(oldInspectionTechnology.getDescription());
            newInspectionTechnology.setEnterprise(oldInspectionTechnology.getEnterprise());
        }
        Long timeStamp = System.currentTimeMillis();
        modelAndView.addObject("timeStamp",timeStamp);
        modelAndView.addObject("oldId", oldInspectionTechnology.getId()+"");
        modelAndView.addObject("inspectionTechnology",newInspectionTechnology);
        String rootCatId = "";
        if(newInspectionTechnology.getFacilityCat()!=null){
            FacilityCat rootCat = facilityCatBiz.findRootCat(newInspectionTechnology.getFacilityCat().getId());
            rootCatId = rootCat.getId()+"";
        }
        modelAndView.addObject("rootCatId",rootCatId);
        modelAndView.setViewName("pages/admin/inspection/inspectionTechnology/edit");

        return modelAndView;
    }

    /**
     * 执行提交的新增或修改请求
     */
    @RequestMapping("/executeEdit")
    @ResponseBody
    public ResultDto executeEdit(InspectionTechnology inspectionTechnology,
                                 @RequestParam(value = "timeStamp", required = false) String timeStamp,
                                 @RequestParam(value = "oldId", required = false) String oldId,
                                 @RequestParam(value = "selectCatId[]", required = false) List<String> selectCatIds,
                                 @RequestParam(value = "selectRootCatId[]", required = false) List<String> selectRootCatIds,
                                 @RequestParam(value = "selectOrganizationId[]", required = false) List<String> selectOrganizationIds,
                                 HttpServletRequest request) {
        InspectionTechnology oldInspectionTechnology;
        if(!StringUtils.isEmpty(oldId)){
            oldInspectionTechnology = inspectionTechnologyBiz.findModel(Long.valueOf(oldId));
        }else{
            oldInspectionTechnology=new InspectionTechnology();
        }

        if (!StringUtils.isBlank(oldId)) {
            inspectionTechnology.setOrganization(oldInspectionTechnology.getOrganization());
        }


        if(StringUtils.isBlank(timeStamp)){
            return ResultUtil.error("参数异常");
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("获取企业失败，请更新页面重试");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if(systemUser==null){
            return ResultUtil.error("获取用户信息失败，请更新页面重试");
        }
        if(selectRootCatIds!=null &&selectCatIds == null && inspectionTechnology.getOrganization() == null){
            return ResultUtil.error("请选择设备类型，或取消选择设备专业");
        }
        if (CollectionUtils.isNotEmpty(selectCatIds)) {
            inspectionTechnology.setFacilityCat(facilityCatBiz.findModel(StringConverters.ToLong(selectCatIds.get(0))));
        } else if (CollectionUtils.isNotEmpty(selectCatIds) && oldInspectionTechnology.getFacilityCat() != null) {
            inspectionTechnology.setFacilityCat(oldInspectionTechnology.getFacilityCat());
        }
        if (CollectionUtils.isNotEmpty(selectOrganizationIds)) {
            inspectionTechnology.setOrganization(organizationBiz.findModel(StringConverters.ToLong(selectOrganizationIds.get(0))));
        }else{
            return ResultUtil.error("请选择部门");
        }
        QueryParam queryParamT = new QueryParam();
        queryParamT.getSqlMap().put("timeStamp",timeStamp);
        queryParamT.getSqlMap().put("enterpriseId",enterprise.getId()+"");
        List<InspectionData> inspectionDataListT = inspectionDataBiz.findList(queryParamT);
        if(inspectionTechnology.getId()==null){
            if(CollectionUtils.isEmpty(inspectionDataListT)){
                return ResultUtil.error("请添加至少一个巡检内容");
            }
        }else{
            QueryParam queryParamO = new QueryParam();
            queryParamO.getSqlMap().put("inspectionTechnologyId",inspectionTechnology.getId()+"");
            queryParamO.getSqlMap().put("enterpriseId",enterprise.getId()+"");
            List<InspectionData> inspectionDataListO = inspectionDataBiz.findList(queryParamO);
            if(CollectionUtils.isEmpty(inspectionDataListT)&&CollectionUtils.isEmpty(inspectionDataListO)){
                return ResultUtil.error("请添加至少一个巡检内容");
            }
        }
//        if(inspectionTechnology.getId()==null&&CollectionUtils.isEmpty(inspectionDataListT)){
//            return ResultUtil.error("请添加至少一个巡检内容");
//        }
        if(inspectionTechnology.getId()==null){
            //新增 分配一个流水号
            inspectionTechnology.setCode(inspectionTechnologyBiz.getCode(enterprise.getId()+""));
        }
        inspectionTechnology.setEnterprise(enterprise);
        inspectionTechnologyBiz.addOrUpdate(inspectionTechnology);
        //给本次添加的维保内容绑定ID
        for(InspectionData inspectionData : inspectionDataListT){
            inspectionData.setInspectionTechnology(inspectionTechnology);
            inspectionDataBiz.addOrUpdate(inspectionData);
        }
        //清空无效维保内容
        inspectionDataBiz.deleteUselessData();
        //添加快照
        JSONArray jsonArray = new JSONArray();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("inspectionTechnologyId",inspectionTechnology.getId()+"");
        List<InspectionData> inspectionDataList = inspectionDataBiz.findList(queryParam);
        if(CollectionUtils.isNotEmpty(inspectionDataList)){
            for(InspectionData inspectionData :inspectionDataList){
                JSONObject jsonObject = inspectionData.toJSONObject2();
                jsonArray.add(jsonObject);
            }
        }
        if (oldId == null && "".equals(oldId)) {
            inspectionTechnology.setInspectionDataContent(jsonArray.toString());
        }
        inspectionTechnologyBiz.addOrUpdate(inspectionTechnology);
        return ResultUtil.success();
    }

    /**
     * 删除工艺
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResultDto delete(String id,HttpServletRequest request) {
        InspectionTechnology inspectionTechnology = inspectionTechnologyBiz.findModel(StringConverters.ToLong(id));
        if(inspectionTechnology!=null){
            inspectionTechnologyBiz.deleteLogic(inspectionTechnology);
        }
        return ResultUtil.success();
    }


    /**
     * 上传导入文件
     */
    @RequestMapping("/uploadTechnologyImportFile")
    @ResponseBody
    public ResultDto uploadTechnologyImportFile(HttpServletRequest request,
                                                @RequestParam(value = "file", required = false) MultipartFile file) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (null == enterprise) {
            return ResultUtil.error("当前用户企业信息有误，请退出重新登录");
        }
        if (null != file && !file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String ext = fileName.substring(fileName.lastIndexOf("."));
            try {
                InputStream is = file.getInputStream();
                if (".xls".equals(ext)) {
                    wb = new HSSFWorkbook(is);
                } else if (".xlsx".equals(ext)) {
                    wb = new XSSFWorkbook(is);
                } else {
                    return ResultUtil.error("请导入正确格式的文件（Excel）");
                }
            } catch (Exception e) {
                logger.error("IOException", e);
                return ResultUtil.error("导入失败，请刷新后重试");
            }
        }
        ResultDto resultDto = inspectionTechnologyBiz.checkData(wb,enterprise);
        if (resultDto.getStatus() != 0) {
            return resultDto;
        }
        ThreadUtils.importInspectionTechnologyThread(inspectionTechnologyBiz, wb, enterprise);
        return ResultUtil.success();
    }

    @RequestMapping("/importPage")
    public ModelAndView importPage(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        modelAndView.addObject("enterprise", enterprise);
        modelAndView.setViewName("pages/admin/inspection/inspectionTechnology/import");
        return modelAndView;
    }
}
